// 全局状态对象
const appState = {
    mindmapContainer: null,
    transformer: null,
    currentMarkmapInstance: null,
    isWaitingForResponse: false,
    conversationId: "",
    currentSelectedDemandId: null,
    currentMindmap: null,
};

// 等待markmap库加载完成的函数
function waitForMarkmap() {
    return new Promise((resolve) => {
        const check = () => {
            if (window.markmap && window.markmap.Markmap) {
                resolve();
            } else {
                setTimeout(check, 100);
            }
        };
        check();
    });
}

// DOM 加载完成后执行的初始化函数
function initializeApp() {
    // 初始化mindmap容器
    appState.mindmapContainer = document.getElementById("mindmap-container");

    // 检查mindmap容器
    if (!appState.mindmapContainer) {
        console.error("找不到mindmap-container元素");
        return;
    }

    // 初始化时显示占位符
    appState.mindmapContainer.innerHTML =
        '<div class="mindmap-placeholder">请在右侧输入需求内容，将自动生成思维导图</div>';

    // 用户信息下拉菜单初始化
    initializeUserDropdown();

    // 其他初始化
    initializeEventListeners();
}

// 初始化用户下拉菜单
function initializeUserDropdown() {
    const userInfo = document.querySelector(".user-info");
    const userDropdown = document.querySelector(".user-dropdown");

    if (userInfo && userDropdown) {
        userInfo.addEventListener("click", function (e) {
            e.stopPropagation();
            userDropdown.style.display =
                userDropdown.style.display === "block" ? "none" : "block";
        });

        document.addEventListener("click", function (e) {
            if (!userInfo.contains(e.target)) {
                userDropdown.style.display = "none";
            }
        });
    }
}

// 初始化事件监听器
function initializeEventListeners() {
    // 基础交互逻辑
    const navItems = document.querySelectorAll(".nav-item");
    navItems.forEach((item) => {
        item.addEventListener("click", function () {
            document.querySelector(".nav-item.active")?.classList.remove("active");
            this.classList.add("active");
            toggleSections(this.textContent.trim());

            // 如果点击的是需求维护池，加载需求列表
            if (this.textContent.trim() === "需求维护池") {
                loadUserDemands();
            }
        });
    });

    // 初始化下拉框事件
    initializeDropdowns();

    // 创建需求按钮
    const createBtn = document.querySelector(".create-btn");
    if (createBtn) {
        createBtn.addEventListener("click", async function () {
            try {
                // 验证输入
                const title = document.querySelector(".input-demand").value.trim();
                const description = document
                    .querySelector(".description textarea")
                    .value.trim();

                if (!title) {
                    showNotification("请输入需求标题！", "error");
                    return;
                }

                // 调用创建需求函数
                await createDemand();

                // 切换到需求维护池页面
                const navItems = document.querySelectorAll(".nav-item");
                navItems.forEach((item) => {
                    item.classList.remove("active");
                    if (item.textContent === "需求维护池") {
                        item.classList.add("active");
                    }
                });
                toggleSections("需求维护池");
            } catch (error) {
                console.error("Error:", error);
                showNotification("创建需求失败：" + error.message, "error");
            }
        });
    }
}

// 初始化下拉框
function initializeDropdowns() {
    // 主需求下拉框
    const mainDropdown = document.querySelector(".main-demand-dropdown");
    if (mainDropdown) {
        const dropdownButton = mainDropdown.firstElementChild;
        const dropdownContent = mainDropdown.querySelector(".dropdown-content");

        if (dropdownButton && dropdownContent) {
            // 修改点击事件处理
            dropdownButton.addEventListener("click", async function (e) {
                e.stopPropagation(); // 阻止事件冒泡

                // 切换当前下拉框
                const isVisible = dropdownContent.style.display === "block";

                // 关闭其他所有下拉框
                document.querySelectorAll(".dropdown-content").forEach((content) => {
                    if (content !== dropdownContent) {
                        content.style.display = "none";
                    }
                });

                // 如果当前是隐藏状态，则显示并加载需求列表
                if (!isVisible) {
                    dropdownContent.style.display = "block";
                    await loadUserDemands(); // 加载需求列表
                } else {
                    dropdownContent.style.display = "none";
                }
            });
        }
    }

    // 子需求下拉框
    const subDropdown = document.querySelector(".sub-demand-dropdown");
    if (subDropdown) {
        const dropdownButton = subDropdown.firstElementChild;
        const dropdownContent = subDropdown.querySelector(".dropdown-content");

        if (dropdownButton && dropdownContent) {
            dropdownButton.addEventListener("click", function (e) {
                e.stopPropagation(); // 阻止事件冒泡

                // 切换当前下拉框
                const isVisible = dropdownContent.style.display === "block";

                // 关闭其他所有下拉框
                document.querySelectorAll(".dropdown-content").forEach((content) => {
                    if (content !== dropdownContent) {
                        content.style.display = "none";
                    }
                });

                dropdownContent.style.display = isVisible ? "none" : "block";
            });
        }
    }

    // 点击页面其他地方关闭下拉框
    document.addEventListener("click", function (e) {
        // 如果点击的是下拉框内部元素，不处理
        if (e.target.closest(".dropdown")) {
            return;
        }
        // 关闭所有下拉框
        document.querySelectorAll(".dropdown-content").forEach((content) => {
            content.style.display = "none";
        });
    });
}

// 等待DOM加载完成后再执行初始化
if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", initializeApp);
} else {
    initializeApp();
}

// 基础交互逻辑
const navItems = document.querySelectorAll(".nav-item");
navItems.forEach((item) => {
    item.addEventListener("click", function () {
        document.querySelector(".nav-item.active")?.classList.remove("active");
        this.classList.add("active");
        toggleSections(this.textContent.trim());
    });
});

// 文件上传按钮
const uploadBtn = document.querySelector(".upload-btn");
if (uploadBtn) {
    uploadBtn.addEventListener("click", function () {
        const fileInput = this.querySelector("input");
        if (fileInput) {
            fileInput.click();
        }
    });
}

// 修改密码按钮
const changePasswordBtn = document.getElementById("change-password-btn");
if (changePasswordBtn) {
    changePasswordBtn.addEventListener("click", function () {
        const changePasswordContainer = document.querySelector(
            ".change-password-container"
        );
        if (changePasswordContainer) {
            changePasswordContainer.style.display = "flex";
            userDropdown.style.display = "none";
        }
    });
}

// 返回按钮
const returnToUserInfoBtn = document.getElementById("return-to-user-info");
if (returnToUserInfoBtn) {
    returnToUserInfoBtn.addEventListener("click", function () {
        const changePasswordContainer = document.querySelector(
            ".change-password-container"
        );
        if (changePasswordContainer) {
            changePasswordContainer.style.display = "none";
            userDropdown.style.display = "block";
        }
    });
}

// 获取验证码按钮
const getVerificationCodeBtn = document.getElementById("get-verification-code");
if (getVerificationCodeBtn) {
    getVerificationCodeBtn.addEventListener("click", async function () {
        const userContact = document.getElementById("user-contact-display").value;

        try {
            const response = await fetch("/api/sendVerificationCode", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    account: userEmail, // 使用全局的userEmail变量
                }),
            });

            const result = await response.json();

            if (result.success) {
                showNotification("验证码已发送到您的邮箱，请查收");

                // 倒计时功能
                let countdown = 60;
                this.disabled = true;
                this.textContent = `${countdown}秒后重试`;

                const timer = setInterval(() => {
                    countdown--;
                    this.textContent = `${countdown}秒后重试`;

                    if (countdown <= 0) {
                        clearInterval(timer);
                        this.disabled = false;
                        this.textContent = "获取";
                    }
                }, 1000);
            } else {
                showNotification(result.message || "验证码发送失败", "error");
            }
        } catch (error) {
            console.error("Error sending verification code:", error);
            showNotification("验证码发送失败，请稍后重试", "error");
        }
    });
}

// 确认修改密码按钮
const confirmChangePasswordBtn = document.getElementById(
    "confirm-change-password"
);
if (confirmChangePasswordBtn) {
    confirmChangePasswordBtn.addEventListener("click", async function () {
        const verificationCode = document.getElementById("verification-code").value;
        const newPassword = document.getElementById("new-password").value;
        const confirmPassword = document.getElementById("confirm-password").value;

        // 前端验证
        if (!verificationCode) {
            showNotification("请输入验证码", "error");
            return;
        }

        if (!newPassword) {
            showNotification("请输入新密码", "error");
            return;
        }

        if (!confirmPassword) {
            showNotification("请确认新密码", "error");
            return;
        }

        if (newPassword !== confirmPassword) {
            showNotification("两次输入的密码不一致", "error");
            return;
        }

        if (newPassword.length < 6) {
            showNotification("密码长度不能少于6位", "error");
            return;
        }

        try {
            const response = await fetch("/api/changePassword", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    account: userEmail,
                    verificationCode: verificationCode,
                    newPassword: newPassword,
                    confirmPassword: confirmPassword,
                }),
            });

            const result = await response.json();

            if (result.success) {
                showNotification("密码修改成功");
                // 清空输入框
                document.getElementById("verification-code").value = "";
                document.getElementById("new-password").value = "";
                document.getElementById("confirm-password").value = "";
                // 关闭修改密码界面
                document.querySelector(".change-password-container").style.display =
                    "none";
            } else {
                showNotification(result.message || "密码修改失败", "error");
            }
        } catch (error) {
            console.error("Error changing password:", error);
            showNotification("密码修改失败，请稍后重试", "error");
        }
    });
}

// 初始化用户信息显示
const userEmailSpan = document.getElementById("userEmail");
const userContactSpan = document.getElementById("userContact");
if (userEmailSpan && userEmail) {
    userEmailSpan.textContent = userEmail;
}
if (userContactSpan && userEmail) {
    userContactSpan.textContent = userEmail;
}

const inputDemand = document.getElementById("input-demand");
const confirmSubBtn = document.getElementById("confirmsub-btn");
const demandDescription = document.getElementById("demand-description");
const demandDescriptionone = document.getElementById("demand-description-one");
const mindmapContainer = document.getElementById("mindmap-container");

// 点击页面其他地方关闭所有下拉框
document.addEventListener("click", function () {
    const dropdowns = document.querySelectorAll(".dropdown-content");
    dropdowns.forEach((dropdown) => {
        dropdown.style.display = "none";
    });
});

// 初始状态显示提示信息
const rightContent = document.querySelector(".right-content");
if (rightContent) {
    const overview = rightContent.querySelector(".overview h3");
    if (overview) {
        overview.textContent = "请选择需求";
    }
}

// 创建需求的函数
async function createDemand() {
    try {
        if (!appState.mindmapContainer) {
            appState.mindmapContainer = document.getElementById("mindmap-container");
            if (!appState.mindmapContainer) {
                console.error("找不到mindmap-container元素");
                showNotification("系统错误：找不到思维导图容器", "error");
                return;
            }
        }

        // 获取需求数据
        const title = document.querySelector(".input-demand").value.trim();
        const description = document
            .querySelector(".description textarea")
            .value.trim();

        // 验证数据
        if (!title) {
            showNotification("请输入需求标题！", "error");
            return;
        }

        // 获取脑图数据
        let mindMapData = "";
        try {
            if (
                appState.currentMarkmapInstance &&
                appState.currentMarkmapInstance.state &&
                appState.currentMarkmapInstance.state.data
            ) {
                mindMapData = JSON.stringify(
                    appState.currentMarkmapInstance.state.data
                );
            } else if (appState.mindmapContainer.querySelector("svg")) {
                mindMapData = appState.mindmapContainer.querySelector("svg").outerHTML;
            }
        } catch (mindmapError) {
            console.warn("获取脑图数据失败:", mindmapError);
        }

        // 构建需求对象
        const demand = {
            title: title,
            description: description,
            mindMapData: mindMapData,
            creatorId: userId,
            status: "PUBLISHED", // 设置状态为已发布
        };

        console.log("Creating demand with data:", demand);

        // 创建主需求
        const response = await fetch("/api/demands?creatorId=" + userId, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(demand),
        });

        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`创建需求失败: ${errorText}`);
        }

        const mainDemand = await response.json();
        showNotification("主需求创建成功！");

        // 调用子需求生成API - 修复请求格式
        const childReqResponse = await fetch("/api/child-requirements", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                inputs: {},
                query: description || title, // 使用需求描述作为query，如果没有描述则使用标题
                response_mode: "streaming",
                conversation_id: "",
                user: userId,
                files: [],
            }),
        });

        if (!childReqResponse.ok) {
            const errorText = await childReqResponse.text();
            throw new Error(`生成子需求失败: ${errorText}`);
        }

        const childReqData = await childReqResponse.json();
        console.log("子需求接口返回数据:", childReqData);

        // 解析返回的数据 - 修复数据解析逻辑
        let childRequirements = [];
        try {
            if (
                childReqData &&
                childReqData.sub_requirements &&
                Array.isArray(childReqData.sub_requirements)
            ) {
                childRequirements = childReqData.sub_requirements;
            } else {
                console.warn("接口返回的子需求数据格式不正确:", childReqData);
                showNotification("子需求数据格式异常，但主需求已创建成功", "warning");
                return;
            }
        } catch (e) {
            console.error("解析子需求数据失败:", e);
            showNotification("解析子需求数据失败，但主需求已创建成功", "warning");
            return;
        }

        // 创建子需求
        if (childRequirements.length > 0) {
            let successCount = 0;
            for (const childReq of childRequirements) {
                try {
                    const childDemand = {
                        title: childReq.title || "未命名子需求",
                        description: childReq.description || "",
                        mindMapData: "", // 子需求暂时不生成脑图
                        creatorId: userId,
                        parentId: mainDemand.id,
                        status: "DRAFT", // 子需求默认为草稿状态
                        originalId: childReq.id, // 保存原始ID用于后续引用
                    };

                    const childResponse = await fetch(
                        "/api/demands?creatorId=" + userId,
                        {
                            method: "POST",
                            headers: {
                                "Content-Type": "application/json",
                            },
                            body: JSON.stringify(childDemand),
                        }
                    );

                    if (childResponse.ok) {
                        successCount++;
                    } else {
                        console.error("创建子需求失败:", childReq.title);
                    }
                } catch (childError) {
                    console.error("创建子需求异常:", childError);
                }
            }

            showNotification(
                `子需求生成完成！成功创建 ${successCount}/${childRequirements.length} 个子需求`
            );
        } else {
            showNotification("未生成子需求，但主需求已创建成功", "warning");
        }

        // 清空输入框和脑图
        document.querySelector(".input-demand").value = "";
        document.querySelector(".description textarea").value = "";
        appState.mindmapContainer.innerHTML =
            '<div class="mindmap-placeholder">请在右侧输入需求内容，将自动生成思维导图</div>';
        appState.currentMarkmapInstance = null;
    } catch (error) {
        console.error("Error:", error);
        showNotification("创建需求失败：" + error.message, "error");
    }
}

// 切换显示的部分
function toggleSections(activeTab) {
    const container = document.querySelector(".container");
    const maintenanceContainer = document.querySelector(".maintenance-container");
    const messagesContainer = document.querySelector(".messages-container");
    const changePasswordContainer = document.querySelector(
        ".change-password-container"
    );
    container.style.display = "none";
    maintenanceContainer.style.display = "none";
    messagesContainer.style.display = "none";
    changePasswordContainer.style.display = "none";

    if (activeTab === "需求维护池") {
        maintenanceContainer.style.display = "flex";
    } else if (activeTab === "消息") {
        messagesContainer.style.display = "flex";
        // 加载消息列表
        loadUserDemandsAndComments();
    } else {
        container.style.display = "flex";
    }
}
// 全局变量用于存储当前选中的需求
let currentSelectedDemand = null;
let currentSelectedSubDemand = null;
let currentMarkmap = null; // 用于存储当前的markmap实例

// 初始化下拉菜单事件监听
function initializeDropdowns() {
    // 主需求下拉菜单点击事件
    const mainDropdown = document.querySelector(".main-demand-dropdown");
    const mainDropdownContent = mainDropdown?.querySelector(".dropdown-content");

    if (mainDropdown && mainDropdownContent) {
        mainDropdown.addEventListener("click", (e) => {
            e.stopPropagation();
            toggleDropdown(mainDropdownContent);
        });
    }

    // 子需求下拉菜单点击事件
    const subDropdown = document.querySelector(".sub-demand-dropdown");
    const subDropdownContent = subDropdown?.querySelector(".dropdown-content");

    if (subDropdown && subDropdownContent) {
        subDropdown.addEventListener("click", (e) => {
            e.stopPropagation();
            toggleDropdown(subDropdownContent);
        });
    }

    // 点击页面其他地方关闭下拉菜单
    document.addEventListener("click", () => {
        closeAllDropdowns();
    });
}

// 切换下拉菜单显示/隐藏
function toggleDropdown(dropdownContent) {
    const isVisible = dropdownContent.style.display === "block";

    // 先关闭所有下拉菜单
    closeAllDropdowns();

    // 然后显示当前点击的下拉菜单
    if (!isVisible) {
        dropdownContent.style.display = "block";
    }
}

// 关闭所有下拉菜单
function closeAllDropdowns() {
    document.querySelectorAll(".dropdown-content").forEach((content) => {
        content.style.display = "none";
    });
}

// 渲染Markmap思维导图
function renderMarkmap(markdownContent) {
    try {
        const mindmapContainer = document.getElementById("load-mindmap-container");
        if (!mindmapContainer) {
            console.error("Mindmap container not found");
            return;
        }

        // 清空容器
        mindmapContainer.innerHTML = "";

        // 创建SVG元素
        const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
        svg.style.width = "100%";
        svg.style.height = "100%";
        mindmapContainer.appendChild(svg);

        // 如果没有内容，显示占位符
        if (!markdownContent || markdownContent.trim() === "") {
            mindmapContainer.innerHTML =
                '<div class="mindmap-placeholder">暂无思维导图内容</div>';
            return;
        }

        // 使用markmap渲染
        const { markmap } = window;
        if (!markmap) {
            console.error("Markmap library not loaded");
            mindmapContainer.innerHTML =
                '<div class="mindmap-placeholder">思维导图库未加载</div>';
            return;
        }

        // 转换markdown为markmap数据
        const transformer = new markmap.Transformer();
        const { root, features } = transformer.transform(markdownContent);

        // 加载所需的assets
        const { styles, scripts } = transformer.getUsedAssets(features);

        // 如果有之前的markmap实例，先销毁
        if (currentMarkmap) {
            currentMarkmap.destroy();
        }

        // 创建新的markmap实例
        currentMarkmap = markmap.Markmap.create(svg, {
            duration: 500,
            maxWidth: 300,
            spacingVertical: 8,
            spacingHorizontal: 120,
            initialExpandLevel: 2,
            pan: true,
            zoom: true,
        });

        // 渲染数据
        currentMarkmap.setData(root);
        currentMarkmap.fit();
    } catch (error) {
        console.error("Error rendering markmap:", error);
        const mindmapContainer = document.getElementById("load-mindmap-container");
        if (mindmapContainer) {
            mindmapContainer.innerHTML =
                '<div class="mindmap-placeholder">思维导图渲染失败</div>';
        }
    }
}

// 加载用户需求列表 - 修复版本
async function loadUserDemands() {
    try {
        console.log("Loading demands for user:", userId);
        const mainDropdown = document.querySelector(".main-demand-dropdown");
        const mainDropdownContent =
            mainDropdown?.querySelector(".dropdown-content");

        if (!mainDropdownContent) {
            console.error("Main dropdown content container not found");
            return;
        }

        // 显示加载中状态
        mainDropdownContent.innerHTML =
            '<div style="padding: 8px 12px; color: #999;">加载中...</div>';

        // 使用新的API端点获取顶级需求
        const response = await fetch(`/api/demands/creator/${userId}/list`, {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
            credentials: "include",
        });

        console.log("API Response status:", response.status);

        if (!response.ok) {
            if (response.status === 403) {
                throw new Error("没有权限访问需求列表");
            } else if (response.status === 401) {
                throw new Error("请先登录");
            }
            throw new Error(`获取需求列表失败: ${response.status}`);
        }

        const demands = await response.json();
        console.log("Loaded demands:", demands);

        // 清空下拉内容
        mainDropdownContent.innerHTML = "";

        if (!demands || demands.length === 0) {
            const noDemandsDiv = document.createElement("div");
            noDemandsDiv.textContent = "暂无需求";
            noDemandsDiv.className = "dropdown-item no-data";
            mainDropdownContent.appendChild(noDemandsDiv);
            return;
        }

        // 添加需求到下拉菜单
        demands.forEach((demand) => {
            const demandDiv = document.createElement("div");
            demandDiv.textContent = demand.title;
            demandDiv.className = "dropdown-item";
            demandDiv.dataset.demandId = demand.id;

            // 检查是否为当前选中项
            if (currentSelectedDemand && currentSelectedDemand.id === demand.id) {
                demandDiv.classList.add("selected");
            }

            // 添加悬停效果
            demandDiv.addEventListener("mouseover", () => {
                if (!demandDiv.classList.contains("selected")) {
                    demandDiv.classList.add("hover");
                }
            });

            demandDiv.addEventListener("mouseout", () => {
                demandDiv.classList.remove("hover");
            });

            // 点击事件
            demandDiv.addEventListener("click", async (e) => {
                e.stopPropagation();
                await selectMainDemand(demand, demandDiv);
            });

            mainDropdownContent.appendChild(demandDiv);
        });
    } catch (error) {
        console.error("Error loading demands:", error);
        const mainDropdownContent = document.querySelector(
            ".main-demand-dropdown .dropdown-content"
        );
        if (mainDropdownContent) {
            mainDropdownContent.innerHTML = `<div class="dropdown-item error">${
                error.message || "加载失败，请重试"
            }</div>`;
        }
        showNotification(error.message || "获取需求列表失败", "error");
    }
}

// 选择主需求 - 修复版本
async function selectMainDemand(demand, demandDiv) {
    try {
        // 更新选中状态
        document
            .querySelectorAll(".main-demand-dropdown .dropdown-item")
            .forEach((item) => {
                item.classList.remove("selected");
            });
        demandDiv.classList.add("selected");
        currentSelectedDemand = demand;

        // 更新下拉框显示的文本
        const mainDropdown = document.querySelector(".main-demand-dropdown");
        const dropdownText = mainDropdown.querySelector(".dropdown-text");
        if (dropdownText) {
            dropdownText.textContent = demand.title;
        } else {
            const textNode = Array.from(mainDropdown.childNodes).find(
                (node) => node.nodeType === 3
            );
            if (textNode) {
                textNode.textContent = demand.title;
            } else {
                const span = document.createElement("span");
                span.className = "dropdown-text";
                span.textContent = demand.title;
                mainDropdown.insertBefore(span, mainDropdown.firstChild);
            }
        }

        // 关闭下拉菜单
        closeAllDropdowns();

        // 切换到需求维护页面
        document.querySelector(".container").style.display = "none";
        document.querySelector(".messages-container").style.display = "none";

        // 初始化维护页面内容
        const maintenanceContainer = document.querySelector(
            ".maintenance-container"
        );
        maintenanceContainer.style.display = "flex";

        // 激活概览选项
        document
            .querySelectorAll(".left-nav .option")
            .forEach((opt) => opt.classList.remove("active"));
        document.getElementById("overview-option").classList.add("active");

        // 初始化右侧内容区域
        const rightContent = maintenanceContainer.querySelector(".right-content");
        rightContent.innerHTML = `
            <div class="overview">
              <h3 style="margin-bottom: 12px; color: #333;">加载中...</h3>
            </div>
            <div class="horizontal-layout">
              <div class="mind-map">
                <h3 style="margin-bottom: 12px; color: #333">需求脑图</h3>
                <div id="maintenance-mindmap-container-one" class="mindmap-container">
                  <div class="mindmap-placeholder">加载中...</div>
                </div>
              </div>
              <div class="description">
                <h3 style="margin-bottom: 12px; color: #333">需求描述</h3>
                <textarea id="demand-description-one" placeholder="请输入详细的需求描述..."></textarea>
              </div>
            </div>
            <div class="history-section">
              <h3 style="margin-bottom: 12px; color: #333">历史修改：</h3>
              <div class="history-item">
                <div class="content">加载中...</div>
              </div>
            </div>
            <div style="text-align: right;">
                <button class="save-btn">保存</button>
            </div>
        `;

        // 加载主需求详情
        await loadDemandDetails(demand.id);

        // 加载子需求列表
        await loadSubDemands(demand.id);
    } catch (error) {
        console.error("Error handling demand selection:", error);
        showNotification(error.message || "处理需求选择失败", "error");
    }
}

// 加载子需求列表 - 修复版本
async function loadSubDemands(parentId) {
    try {
        const subResponse = await fetch(`/api/demands/parent/${parentId}`, {
            credentials: "include",
        });

        if (subResponse.ok) {
            const subDemands = await subResponse.json();
            const subDropdown = document.querySelector(".sub-demand-dropdown");
            const subDropdownContent =
                subDropdown?.querySelector(".dropdown-content");

            if (subDropdownContent) {
                // 清空子需求下拉内容
                subDropdownContent.innerHTML = "";

                // 重置子需求下拉框显示文本
                const firstChild = subDropdown.firstElementChild;
                if (firstChild && !firstChild.classList.contains("dropdown-content")) {
                    firstChild.textContent = "下拉选择子需求";
                }

                currentSelectedSubDemand = null;

                if (!subDemands || subDemands.length === 0) {
                    const noSubDemandsDiv = document.createElement("div");
                    noSubDemandsDiv.textContent = "暂无子需求";
                    noSubDemandsDiv.className = "dropdown-item no-data";
                    subDropdownContent.appendChild(noSubDemandsDiv);
                } else {
                    subDemands.forEach((subDemand) => {
                        const subDemandDiv = document.createElement("div");
                        subDemandDiv.textContent = subDemand.title;
                        subDemandDiv.className = "dropdown-item";
                        subDemandDiv.dataset.demandId = subDemand.id;

                        // 添加悬停效果
                        subDemandDiv.addEventListener("mouseover", () => {
                            if (!subDemandDiv.classList.contains("selected")) {
                                subDemandDiv.classList.add("hover");
                            }
                        });

                        subDemandDiv.addEventListener("mouseout", () => {
                            subDemandDiv.classList.remove("hover");
                        });

                        subDemandDiv.addEventListener("click", (e) => {
                            e.stopPropagation();
                            selectSubDemand(subDemand, subDemandDiv);
                        });

                        subDropdownContent.appendChild(subDemandDiv);
                    });
                }
            }
        } else {
            console.error("Failed to load sub-demands:", subResponse.status);
            showNotification("加载子需求失败", "error");
        }
    } catch (error) {
        console.error("Error loading sub-demands:", error);
        showNotification("加载子需求失败", "error");
    }
}

// 选择子需求 - 修复版本（关键修复）
async function selectSubDemand(subDemand, subDemandDiv) {
    try {
        // 更新选中状态
        document
            .querySelectorAll(".sub-demand-dropdown .dropdown-item")
            .forEach((item) => {
                item.classList.remove("selected");
            });
        subDemandDiv.classList.add("selected");
        currentSelectedSubDemand = subDemand;

        // 更新下拉框显示的文本
        const subDropdown = document.querySelector(".sub-demand-dropdown");
        const firstChild = subDropdown.firstElementChild;
        if (firstChild && !firstChild.classList.contains("dropdown-content")) {
            firstChild.textContent = subDemand.title;
        }

        // 关闭下拉菜单
        closeAllDropdowns();

        // 清空现有描述以防止显示旧内容
        const textarea = document.querySelector("#demand-description-one");
        if (textarea) {
            textarea.value = "";
        }

        // 加载需求详情并触发实时渲染
        await loadDemandDetails(subDemand.id);
    } catch (error) {
        console.error("Error selecting sub-demand:", error);
        showNotification("选择子需求失败", "error");
    }
}

// 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", () => {
    initializeDropdowns();
});
// 加载需求详细信息
async function loadDemandDetails(demandId) {
    try {
        const response = await fetch(`/api/demands/${demandId}/details`);

        if (!response.ok) {
            throw new Error("获取需求详情失败");
        }

        const demand = await response.json();

        // 更新标题
        const overview = document.querySelector(
            ".maintenance-container .overview h3"
        );
        if (overview) {
            overview.textContent = demand.title;
        }

        // 更新需求描述
        const descriptionTextarea = document.querySelector(
            ".maintenance-container .description textarea"
        );
        if (descriptionTextarea) {
            descriptionTextarea.value = demand.description || "";
            // 触发描述文本变化事件，自动生成思维导图
            const event = new Event("input", { bubbles: true });
            descriptionTextarea.dispatchEvent(event);
        }

        // 更新历史修改记录
        const historySection = document.querySelector(".history-section");
        if (historySection && demand.history) {
            const historyContent = demand.history
                .map(
                    (item) => `
        <div class="history-item">
          <div class="content">修改人：${item.modifier}</div>
          <div class="content">修改时间：${formatDateTime(
                        item.modifiedTime
                    )}</div>
          <div class="content">修改内容：${item.changes}</div>
        </div>
      `
                )
                .join("");
            historySection.innerHTML = `
        <h3 style="margin-bottom: 12px; color: #333;">历史修改：</h3>
        ${
                historyContent ||
                '<div class="history-item"><div class="content">暂无修改记录</div></div>'
            }
      `;
        }

        // 加载历史记录
        await loadDemandHistory(demandId);

        // 绑定保存按钮事件
        const saveBtn = document.querySelector(".save-btn");
        if (saveBtn) {
            saveBtn.onclick = () => saveDemandChanges(demandId);
        }
    } catch (error) {
        console.error("Error:", error);
        showNotification("获取需求详情失败：" + error.message, "error");
    }
}

// 头像上传相关功能
document
    .getElementById("uploadAvatarBtn")
    .addEventListener("click", function (e) {
        e.preventDefault();
        document.getElementById("avatarInput").click();
    });

// 文件上传处理
document
    .getElementById("avatarInput")
    .addEventListener("change", async function (e) {
        const file = e.target.files[0];
        if (!file) return;

        // 验证文件类型
        if (!file.type.startsWith("image/")) {
            showNotification("请选择图片文件！", "error");
            return;
        }

        // 验证文件大小（限制为2MB）
        if (file.size > 2 * 1024 * 1024) {
            showNotification("图片大小不能超过2MB！", "error");
            return;
        }

        try {
            // 创建FormData对象
            const formData = new FormData();
            formData.append("avatar", file);
            formData.append("userId", userId); // 使用实际的用户ID

            // 调用后端API上传头像
            const response = await fetch("/api/user/avatar", {
                method: "POST",
                body: formData,
            });

            if (!response.ok) {
                const result = await response.json();
                throw new Error(result.message || "上传失败");
            }

            const result = await response.json();
            console.log("Upload response:", result);

            // 更新头像显示
            if (result.avatarUrl) {
                // 直接使用返回的avatarUrl，它现在指向新的端点
                const avatarUrl = result.avatarUrl;
                console.log("Avatar URL:", avatarUrl);

                const avatarElement = document.querySelector(".avatar");
                avatarElement.style.backgroundImage = `url('${avatarUrl}')`;
                avatarElement.classList.add("has-image");
                showNotification("头像上传成功！");
            }
        } catch (error) {
            console.error("Upload error:", error);
            showNotification("上传头像失败：" + error.message, "error");
        }
    });

// 页面加载时获取用户信息
async function loadUserInfo() {
    try {
        const response = await fetch(`/api/user/info?userId=${userId}`);
        if (!response.ok) {
            throw new Error("获取用户信息失败");
        }

        const userInfo = await response.json();
        console.log("User info:", userInfo);

        // 更新用户信息显示
        document.getElementById("userContact").textContent =
            userInfo.contact || "未设置";
        document.getElementById("userEmail").textContent =
            userInfo.contact || "未设置";

        // 更新头像显示
        const avatarElement = document.querySelector(".avatar");
        if (userInfo.avatarUrl) {
            // 直接使用返回的avatarUrl，它现在指向新的端点
            const avatarUrl = userInfo.avatarUrl;
            console.log("Loading avatar from:", avatarUrl);
            avatarElement.style.backgroundImage = `url('${avatarUrl}')`;
            avatarElement.classList.add("has-image");
        } else {
            avatarElement.style.backgroundImage = "none";
            avatarElement.classList.remove("has-image");
        }
    } catch (error) {
        console.error("Error loading user info:", error);
    }
}

// 页面加载完成后执行
document.addEventListener("DOMContentLoaded", loadUserInfo);

// 回复按钮逻辑
document.querySelectorAll(".reply-btn").forEach((button) => {
    button.addEventListener("click", function () {
        const replyBox = this.parentElement.parentElement.nextElementSibling;
        replyBox.style.display =
            replyBox.style.display === "flex" ? "none" : "flex";
    });
});

// 格式化时间函数
function formatDateTime(dateStr) {
    if (!dateStr) {
        console.log("formatDateTime: received null or empty dateStr");
        return "未知时间";
    }
    try {
        console.log("formatDateTime: processing date string:", dateStr);
        // 处理后端返回的LocalDateTime格式 (例如: "2024-03-14T10:30:00")
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) {
            console.log("formatDateTime: invalid date object created from:", dateStr);
            return "未知时间";
        }
        const now = new Date();
        const diff = now - date;

        // 小于1分钟
        if (diff < 60000) {
            return "刚刚";
        }
        // 小于1小时
        if (diff < 3600000) {
            return `${Math.floor(diff / 60000)}分钟前`;
        }
        // 小于24小时
        if (diff < 86400000) {
            return `${Math.floor(diff / 3600000)}小时前`;
        }
        // 小于7天
        if (diff < 604800000) {
            return `${Math.floor(diff / 86400000)}天前`;
        }

        // 超过7天显示具体日期时间
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");

        return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (error) {
        console.error("日期格式化错误:", error, "原始日期字符串:", dateStr);
        return "未知时间";
    }
}

// 添加一个变量来跟踪当前选中的需求ID
let currentSelectedDemandId = null;

// 显示需求消息
async function showDemandMessages(demandId, demandTitle) {
    try {
        currentSelectedDemandId = demandId;

        document.querySelector(".container").style.display = "none";
        document.querySelector(".maintenance-container").style.display = "none";
        const messagesContainer = document.querySelector(".messages-container");
        messagesContainer.style.display = "flex";

        // 只显示需求标题
        const demandHeader = document.querySelector(".demand-header");
        demandHeader.innerHTML = `<div class="demand-name">${demandTitle}</div>`;

        // 获取需求的所有评论
        const response = await fetch(`/api/comments/demand/${demandId}`);
        if (!response.ok) {
            throw new Error("获取评论失败");
        }
        const comments = await response.json();

        // 更新评论总数
        document.querySelector(".total-comments").textContent = comments.length;

        // 清空消息列表
        const messageList = document.querySelector(".message-list");
        messageList.innerHTML = "";

        // 组织评论数据：区分主评论和回复
        const mainComments = comments.filter((comment) => !comment.parentId);
        const replies = comments.filter((comment) => comment.parentId);

        // 获取所有用户信息并创建映射
        const userIds = [...new Set(comments.map((comment) => comment.userId))];
        const userInfoPromises = userIds.map(async (userId) => {
            try {
                const response = await fetch(`/api/user/info?userId=${userId}`);
                if (!response.ok) {
                    console.warn(`Failed to fetch user info for userId: ${userId}`);
                    return [userId, null];
                }
                const userInfo = await response.json();
                return [userId, userInfo];
            } catch (error) {
                console.warn(`Error fetching user info for userId: ${userId}`, error);
                return [userId, null];
            }
        });

        const userInfoResults = await Promise.all(userInfoPromises);
        const userMap = Object.fromEntries(userInfoResults);

        // 渲染主评论
        for (const comment of mainComments) {
            const user = userMap[comment.userId] || {
                username: "未知用户",
                avatarUrl: "/images/default-avatar.png",
            };
            const commentReplies = replies.filter(
                (reply) => reply.parentId === comment.id
            );

            const commentElement = createCommentElement(
                comment,
                user,
                commentReplies,
                userMap
            );
            messageList.appendChild(commentElement);
        }
    } catch (error) {
        console.error("Error:", error);
        showNotification(error.message || "加载评论失败", "error");
    }
}

// 创建评论元素
function createCommentElement(comment, user, replies, userMap) {
    const div = document.createElement("div");
    div.className = "comment-item";

    const defaultUser = {
        username: "未知用户",
        avatarUrl: "/images/default-avatar.png",
    };

    // 确保有用户信息
    const commentUser = user || defaultUser;

    // 默认只显示前2条回复
    const initialRepliesCount = 2;
    const hasMoreReplies = replies && replies.length > initialRepliesCount;
    const initialReplies = replies ? replies.slice(0, initialRepliesCount) : [];
    const remainingReplies = replies ? replies.slice(initialRepliesCount) : [];

    div.innerHTML = `
    <div class="comment-avatar">
      <img src="${commentUser.avatarUrl || "/images/default-avatar.png"}" 
           alt="用户头像"
           onerror="this.src='/images/default-avatar.png'">
    </div>
    <div class="comment-content">
      <div class="comment-header">
        <span class="comment-user">${commentUser.username || "未知用户"}</span>
        <span class="comment-time">${formatDateTime(comment.createdTime)}</span>
      </div>
      <div class="comment-text">${comment.content || ""}</div>
      <div class="comment-actions">
        <button class="reply-button" onclick="toggleReplyBox(${
        comment.id
    })">回复</button>
      </div>
      <div class="reply-box" id="replyBox${comment.id}" style="display: none;">
        <div class="reply-input-container">
          <textarea class="reply-textarea" placeholder="回复 ${
        commentUser.username
    }..."></textarea>
          <button class="confirm-btn" onclick="submitReply(${comment.id}, '${
        commentUser.username
    }')">发送</button>
        </div>
      </div>
      ${
        replies && replies.length > 0
            ? `
        <div class="replies-container" id="repliesContainer${comment.id}">
          ${initialReplies
                .map((reply) => {
                    const replyUser = userMap[reply.userId] || defaultUser;
                    return `
              <div class="reply-item">
                <div class="reply-avatar">
                  <img src="${
                        replyUser.avatarUrl || "/images/default-avatar.png"
                    }" 
                       alt="用户头像"
                       onerror="this.src='/images/default-avatar.png'">
                </div>
                <div class="reply-content">
                  <div class="reply-header">
                    <span class="reply-user">${
                        replyUser.username || "未知用户"
                    }</span>
                    <span class="reply-time">${formatDateTime(
                        reply.createdTime
                    )}</span>
                  </div>
                  <div class="reply-text">${reply.content || ""}</div>
                </div>
              </div>
            `;
                })
                .join("")}
          ${
                hasMoreReplies
                    ? `
            <div class="remaining-replies" style="display: none;">
              ${remainingReplies
                        .map((reply) => {
                            const replyUser = userMap[reply.userId] || defaultUser;
                            return `
                  <div class="reply-item">
                    <div class="reply-avatar">
                      <img src="${
                                replyUser.avatarUrl || "/images/default-avatar.png"
                            }" 
                           alt="用户头像"
                           onerror="this.src='/images/default-avatar.png'">
                    </div>
                    <div class="reply-content">
                      <div class="reply-header">
                        <span class="reply-user">${
                                replyUser.username || "未知用户"
                            }</span>
                        <span class="reply-time">${formatDateTime(
                                reply.createdTime
                            )}</span>
                      </div>
                      <div class="reply-text">${reply.content || ""}</div>
                    </div>
                  </div>
                `;
                        })
                        .join("")}
            </div>
            <div class="toggle-replies" onclick="toggleReplies(${comment.id}, ${
                        replies.length
                    })">
              <span class="show-more">显示更多${
                        replies.length - initialRepliesCount
                    }条回复</span>
              <span class="show-less" style="display: none;">收起回复</span>
            </div>
          `
                    : ""
            }
        </div>
      `
            : ""
    }
    </div>
  `;

    return div;
}

// 切换回复框显示状态
function toggleReplyBox(commentId) {
    const replyBox = document.getElementById(`replyBox${commentId}`);
    const allReplyBoxes = document.querySelectorAll(".reply-box");

    // 关闭其他所有回复框
    allReplyBoxes.forEach((box) => {
        if (box.id !== `replyBox${commentId}` && box.id !== "mainReplyBox") {
            box.style.display = "none";
        }
    });

    // 切换当前回复框
    replyBox.style.display = replyBox.style.display === "none" ? "block" : "none";
}

// 提交回复
async function submitReply(parentId, replyToUsername) {
    const replyBox = document.getElementById(`replyBox${parentId}`);
    const textarea = replyBox.querySelector(".reply-textarea");
    const content = textarea.value.trim();

    if (!content) {
        showNotification("请输入回复内容", "error");
        return;
    }

    if (!currentSelectedDemandId) {
        showNotification("未选择需求，无法发送回复", "error");
        return;
    }

    try {
        const comment = {
            demandId: currentSelectedDemandId,
            content: content,
            parentId: parentId,
            userId: userId,
            userName: userEmail,
            createdTime: new Date().toISOString(),
        };

        console.log("Submitting reply:", comment); // Debug log

        const response = await fetch("/api/comments", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(comment),
        });

        if (!response.ok) {
            const errorData = await response.text();
            console.error("Server error:", errorData);
            throw new Error(`发送回复失败: ${errorData}`);
        }

        const result = await response.json();
        console.log("Reply success:", result); // Debug log

        // 清空输入框并刷新评论列表
        textarea.value = "";
        replyBox.style.display = "none";
        showNotification("回复发送成功");
        await showDemandMessages(
            currentSelectedDemandId,
            document.querySelector(".demand-name").textContent
        );
    } catch (error) {
        console.error("Error in submitReply:", error);
        showNotification(error.message || "发送回复失败", "error");
    }
}

// 更新loadUserDemandsAndComments函数
async function loadUserDemandsAndComments() {
    try {
        console.log("Loading demands for user:", userId);

        // 获取用户发布的需求 - 修正API路径
        const response = await fetch(`/api/demands/creator/${userId}/list`);
        console.log("Demands API response status:", response.status);

        if (!response.ok) {
            const errorText = await response.text();
            console.error("API Error:", errorText);
            throw new Error(`获取需求列表失败: ${response.status} ${errorText}`);
        }

        const demands = await response.json();
        console.log("Loaded demands:", demands);

        // 获取需求的最新消息时间
        const demandIds = demands.map((demand) => demand.id);
        if (demandIds.length > 0) {
            console.log("Loading latest messages for demands:", demandIds);

            // 注释掉未读消息相关代码
            /*
                                                                              const latestMessageResponse = await fetch(
                                                                                `/api/comments/demand/latest-time?demandIds=${demandIds.join(",")}`
                                                                              );
                                                                              if (!latestMessageResponse.ok) {
                                                                                console.error(
                                                                                  "Failed to fetch latest message times:",
                                                                                  await latestMessageResponse.text()
                                                                                );
                                                                              }
                                                                              const latestMessageTimes = await latestMessageResponse.json();
                                                                              console.log("Latest message times:", latestMessageTimes);

                                                                              // 获取每个需求的未读消息数
                                                                              console.log("Fetching unread counts for demands");
                                                                              const unreadCountsPromises = demands.map((demand) =>
                                                                                fetch(`/api/comments/demand/${demand.id}/unread/count`)
                                                                                  .then((res) => (res.ok ? res.json() : 0))
                                                                                  .catch((err) => {
                                                                                    console.error(
                                                                                      `Error fetching unread count for demand ${demand.id}:`,
                                                                                      err
                                                                                    );
                                                                                    return 0;
                                                                                  })
                                                                              );
                                                                              const unreadCounts = await Promise.all(unreadCountsPromises);
                                                                              console.log("Unread counts:", unreadCounts);
                                                                              */

            // 清空并重新填充需求列表
            const demandList = document.querySelector(
                ".messages-container .demand-list"
            );
            if (!demandList) {
                console.error("Demand list container not found");
                throw new Error("页面元素未找到");
            }
            demandList.innerHTML = "";

            demands.forEach((demand) => {
                const demandElement = document.createElement("div");
                demandElement.className = "demand-item";
                demandElement.setAttribute("data-demand-id", demand.id);

                demandElement.innerHTML = `
          <span class="title">${demand.title || "未命名需求"}</span>
        `;

                demandElement.addEventListener("click", () => {
                    document.querySelectorAll(".demand-item").forEach((item) => {
                        item.classList.remove("active");
                    });
                    demandElement.classList.add("active");
                    showDemandMessages(demand.id, demand.title || "未命名需求");
                });

                demandList.appendChild(demandElement);
            });
        } else {
            console.log("No demands found");
            const demandList = document.querySelector(
                ".messages-container .demand-list"
            );
            if (!demandList) {
                console.error("Demand list container not found");
                throw new Error("页面元素未找到");
            }
            demandList.innerHTML = '<div class="no-demands">暂无需求</div>';
        }
    } catch (error) {
        console.error("Error in loadUserDemandsAndComments:", error);
        showNotification(
            "加载需求列表失败：" + (error.message || "未知错误"),
            "error"
        );
    }
}

// 确定需求
document
    .querySelector(".confirmsub-btn")
    .addEventListener("click", function () {
        // 模拟获取数据
        const data = {
            mindMap: "这是模拟的需求脑图数据",
            description: "这是模拟的需求描述数据",
        };

        // 更新需求脑图
        const mindMapElement = document.querySelector(".mind-map div");
        mindMapElement.textContent = data.mindMap;

        // 更新需求描述
        const descriptionElement = document.querySelector(".description textarea");
        descriptionElement.value = data.description;
    });

// 下拉菜单显示隐藏
document.querySelectorAll(".dropdown-content div").forEach((item) => {
    item.addEventListener("click", function (e) {
        e.stopPropagation(); // 阻止冒泡到document
        const parentDropdown = this.closest(".dropdown");
        parentDropdown.querySelector(".dropdown-content").style.display = "none";
    });
});
// 动态生成的选项需要事件委托
document.body.addEventListener("click", function (e) {
    if (e.target.closest(".dropdown-content div")) {
        e.stopPropagation();
        const dropdown = e.target.closest(".dropdown");
        dropdown.querySelector(".dropdown-content").style.display = "none";
    }
});
//
document.addEventListener("DOMContentLoaded", function () {
    const mainDemandDropdown = document.querySelector(".main-demand-dropdown");
    const subDemandDropdown = document.querySelector(".sub-demand-dropdown");
    const rightContent = document.querySelector(
        ".maintenance-container .right-content"
    );
    const overviewOption = document.getElementById("overview-option");
    const subDemandOption = document.getElementById("sub-demand-option");
    const overview = document.querySelector(".overview");

    const subDemands = {
        1: ["子需求1-1", "子需求1-2"],
        2: ["子需求2-1", "子需求2-2"],
    };

    // 显示下拉框内容
    mainDemandDropdown.addEventListener("click", function (event) {
        event.stopPropagation(); // 阻止事件冒泡
        const dropdownContent =
            mainDemandDropdown.querySelector(".dropdown-content");
        dropdownContent.style.display =
            dropdownContent.style.display === "block" ? "none" : "block";
    });

    subDemandDropdown.addEventListener("click", function (event) {
        event.stopPropagation(); // 阻止事件冒泡
        const dropdownContent =
            subDemandDropdown.querySelector(".dropdown-content");
        dropdownContent.style.display =
            dropdownContent.style.display === "block" ? "none" : "block";
    });

    // 点击下拉框选项
    mainDemandDropdown
        .querySelector(".dropdown-content")
        .addEventListener("click", function (event) {
            event.stopPropagation(); // 阻止事件冒泡
            const selectedDemandId = event.target.getAttribute("data-demand-id");
            const selectedDemandName = event.target.textContent;

            // 更新子需求下拉框
            const subDropdownContent =
                subDemandDropdown.querySelector(".dropdown-content");
            subDropdownContent.innerHTML = "";

            // 检查subDemands和selectedDemandId是否有效
            if (
                subDemands &&
                subDemands[selectedDemandId] &&
                Array.isArray(subDemands[selectedDemandId])
            ) {
                subDemands[selectedDemandId].forEach((subDemand) => {
                    const div = document.createElement("div");
                    div.textContent = subDemand;
                    subDropdownContent.appendChild(div);
                });
            } else {
                // 如果没有子需求，显示提示信息
                const noSubDemandsDiv = document.createElement("div");
                noSubDemandsDiv.textContent = "暂无子需求";
                noSubDemandsDiv.style.padding = "8px 12px";
                noSubDemandsDiv.style.color = "#999";
                subDropdownContent.appendChild(noSubDemandsDiv);
            }

            // 更新概览
            overview.innerHTML = `<h3 style="margin-bottom: 12px; color: #333;">主需求名称：${selectedDemandName}</h3>`;
        });

    subDemandDropdown
        .querySelector(".dropdown-content")
        .addEventListener("click", function (event) {
            const selectedSubDemand = event.target.textContent;
            overview.innerHTML += `<h3 style="margin-bottom: 12px; color: #333;">子需求名称：${selectedSubDemand}</h3>`;
        });

    // 点击其他地方关闭下拉框
    document.addEventListener("click", function () {
        const dropdowns = document.querySelectorAll(".dropdown-content");
        dropdowns.forEach((dropdown) => {
            dropdown.style.display = "none";
        });
    });

    // 点击概览选项
    overviewOption.addEventListener("click", function () {
        rightContent.innerHTML = `
            <div class="overview">
                <h3 style="margin-bottom: 12px; color: #333;">某需求的概览：</h3>
            </div>
            <div class="horizontal-layout">
                <div class="mind-map">
                    <h3 style="margin-bottom: 12px; color: #333;">需求脑图</h3>
                    <div style="height: calc(100% - 40px); border: 1px dashed #ddd;
                         border-radius: 4px; display: grid; place-items: center;
                         color: #999;">
                        脑图区域（可集成专业脑图库）
                    </div>
                </div>

                <div class="description">
                    <h3 style="margin-bottom: 12px; color: #333;">需求描述</h3>
                    <textarea placeholder="请输入详细的需求描述..."></textarea>
                </div>
            </div>
            <div class="history-section">
                <h3 style="margin-bottom: 12px; color: #333;">历史修改：</h3>
                <div class="history-item">
                    <div class="content">某人修改：</div>
                    <div class="content">原内容：<br>...</div>
                    <div class="content">修改为：<br>...</div>
                </div>
            </div>
            <div style="text-align: right;">
                    <button class="save-btn">保存</button>
            </div>
        `;
    });

    // 点击子需求选项
    subDemandOption.addEventListener("click", function () {
        rightContent.innerHTML = `
            <div class="overview">
                <h3 style="margin-bottom: 12px; color: #333;">子需求名称：</h3>
            </div>
            <div class="horizontal-layout">
                <div class="mind-map">
                    <h3 style="margin-bottom: 12px; color: #333;">需求脑图</h3>
                    <div style="height: calc(100% - 40px); border: 1px dashed #ddd;
                         border-radius: 4px; display: grid; place-items: center;
                         color: #999;">
                        脑图区域（可集成专业脑图库）
                    </div>
                </div>

                <div class="description">
                    <h3 style="margin-bottom: 12px; color: #333;">需求描述</h3>
                    <textarea placeholder="请输入详细的需求描述..."></textarea>
                </div>
            </div>
            <div class="history-section">
                <h3 style="margin-bottom: 12px; color: #333;">历史修改：</h3>
                <div class="history-item">
                    <div class="content">某人修改：</div>
                    <div class="content">原内容：<br>...</div>
                    <div class="content">修改为：<br>...</div>
                </div>
            </div>
            <button class="save-btn">保存</button>
        `;
    });

    // 初始状态显示提示信息
    rightContent.innerHTML =
        '<div class="overview"><h3 style="margin-bottom: 12px; color: #333;">请选择需求</h3></div>';
});

// 修改密码按钮逻辑
document
    .getElementById("change-password-btn")
    .addEventListener("click", function () {
        document.querySelector(".change-password-container").style.display = "flex";
        document.querySelector(".user-dropdown").style.display = "none";
    });

// 返回按钮逻辑
document
    .getElementById("return-to-user-info")
    .addEventListener("click", function () {
        document.querySelector(".change-password-container").style.display = "none";
        document.querySelector(".user-dropdown").style.display = "block";
    });

// 回复按钮逻辑
document.querySelectorAll(".reply-btn").forEach((button) => {
    button.addEventListener("click", function () {
        const replyBox = this.parentElement.querySelector(".reply-box");
        replyBox.style.display =
            replyBox.style.display === "block" ? "none" : "block";
    });
});
// 确认回复按钮逻辑
document.querySelectorAll(".confirm-btn").forEach((button) => {
    button.addEventListener("click", function () {
        const replyTextarea = this.parentElement.querySelector(".reply-textarea");
        const replyContent = replyTextarea.value;

        if (replyContent.trim() === "") {
            showNotification("请输入回复内容", "error");
            return;
        }

        // 这里可以添加将回复内容发送到后端等实际逻辑
        console.log("回复内容:", replyContent);

        // 添加新消息到消息列表
        const messageList =
            this.closest(".right-content").querySelector(".message-list");
        const now = new Date();
        const timeString =
            now.getFullYear() +
            "-" +
            (now.getMonth() + 1).toString().padStart(2, "0") +
            "-" +
            now.getDate().toString().padStart(2, "0") +
            " " +
            now.getHours().toString().padStart(2, "0") +
            ":" +
            now.getMinutes().toString().padStart(2, "0");

        const newMessage = document.createElement("div");
        newMessage.className = "message-item reply-message";
        newMessage.innerHTML = `
                    <div class="sender">专家</div>
                    <div class="content">${replyContent}</div>
                    <div class="time">${timeString}</div>
                `;

        messageList.appendChild(newMessage);

        // 简单隐藏回复框并清空内容
        const replyBox = this.parentElement;
        replyBox.style.display = "none";
        replyTextarea.value = "";

        // 滚动到底部
        messageList.scrollTop = messageList.scrollHeight;
    });
});
document.querySelectorAll(".demand-item").forEach((item) => {
    item.addEventListener("click", function () {
        // 移除所有需求项的active类
        document
            .querySelectorAll(".demand-item")
            .forEach((i) => i.classList.remove("active"));
        // 给当前点击的需求项添加active类
        this.classList.add("active");

        // 更新右侧内容
        const demandName = this.textContent;
        document.querySelector(
            ".demand-name"
        ).textContent = `需求名称：${demandName}`;

        // 清空消息列表
        const messageList = document.querySelector(".message-list");
        messageList.innerHTML = "";

        // 根据不同需求添加不同消息
        if (demandName.includes("需求一")) {
            messageList.innerHTML = `
                        <div class="message-item comment">
                            <div class="sender">用户11111</div>
                            <div class="content">请问这个需求什么时候可以完成？我比较着急。</div>
                            <div class="time">2023-05-20 10:30</div>
                        </div>
                        <div class="message-item reply-message">
                            <div class="sender">我的回复：</div>
                            <div class="content">您好，这个需求我们正在处理中，预计下周可以完成。</div>
                            <div class="time">2023-05-20 11:15</div>
                        </div>
                        <div class="message-item comment">
                            <div class="sender">用户11111</div>
                            <div class="content">好的，谢谢，希望能按时完成。</div>
                            <div class="time">2023-05-20 14:20</div>
                        </div>
                        <div class="message-item reply-message">
                            <div class="sender">我的回复：</div>
                            <div class="content">我们会尽快处理，请您放心。</div>
                            <div class="time">2023-05-20 15:30</div>
                        </div>
                    `;
        } else if (demandName.includes("需求二")) {
            messageList.innerHTML = `
                        <div class="message-item comment">
                            <div class="sender">用户22222</div>
                            <div class="content">这个需求的预算是多少？</div>
                            <div class="time">2023-05-18 09:45</div>
                        </div>
                        <div class="message-item reply-message">
                            <div class="sender">我的回复</div>
                            <div class="content">您好，这个需求的预算大概在5000 - 8000元左右。</div>
                            <div class="time">2023-05-18 10:20</div>
                        </div>
                        <div class="message-item comment">
                            <div class="sender">用户22222</div>
                            <div class="content">好 的，能否提供更详细的预算清单？</div>
                            <div class="time">2023-05-18 14:30</div>
                        </div>
                    `;
        }
    });
});

// 获取验证码按钮逻辑
document
    .getElementById("get-verification-code")
    .addEventListener("click", async function () {
        const userContact = document.getElementById("user-contact-display").value;

        try {
            const response = await fetch("/api/sendVerificationCode", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    account: userEmail, // 使用全局的userEmail变量
                }),
            });

            const result = await response.json();

            if (result.success) {
                showNotification("验证码已发送到您的邮箱，请查收");

                // 倒计时功能
                let countdown = 60;
                this.disabled = true;
                this.textContent = `${countdown}秒后重试`;

                const timer = setInterval(() => {
                    countdown--;
                    this.textContent = `${countdown}秒后重试`;

                    if (countdown <= 0) {
                        clearInterval(timer);
                        this.disabled = false;
                        this.textContent = "获取";
                    }
                }, 1000);
            } else {
                showNotification(result.message || "验证码发送失败", "error");
            }
        } catch (error) {
            console.error("Error sending verification code:", error);
            showNotification("验证码发送失败，请稍后重试", "error");
        }
    });

// 确认修改密码按钮逻辑
document
    .getElementById("confirm-change-password")
    .addEventListener("click", async function () {
        const verificationCode = document.getElementById("verification-code").value;
        const newPassword = document.getElementById("new-password").value;
        const confirmPassword = document.getElementById("confirm-password").value;

        // 前端验证
        if (!verificationCode) {
            showNotification("请输入验证码", "error");
            return;
        }

        if (!newPassword) {
            showNotification("请输入新密码", "error");
            return;
        }

        if (!confirmPassword) {
            showNotification("请确认新密码", "error");
            return;
        }

        if (newPassword !== confirmPassword) {
            showNotification("两次输入的密码不一致", "error");
            return;
        }

        if (newPassword.length < 6) {
            showNotification("密码长度不能少于6位", "error");
            return;
        }

        try {
            const response = await fetch("/api/changePassword", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    account: userEmail,
                    verificationCode: verificationCode,
                    newPassword: newPassword,
                    confirmPassword: confirmPassword,
                }),
            });

            const result = await response.json();

            if (result.success) {
                showNotification("密码修改成功");
                // 清空输入框
                document.getElementById("verification-code").value = "";
                document.getElementById("new-password").value = "";
                document.getElementById("confirm-password").value = "";
                // 关闭修改密码界面
                document.querySelector(".change-password-container").style.display =
                    "none";
            } else {
                showNotification(result.message || "密码修改失败", "error");
            }
        } catch (error) {
            console.error("Error changing password:", error);
            showNotification("密码修改失败，请稍后重试", "error");
        }
    });

// 显示通知的函数
function showNotification(message, type = "success") {
    const notification = document.querySelector(".notification");
    const messageElement = notification.querySelector(".message");
    const iconElement = notification.querySelector(".icon");

    // 设置消息内容和类型
    messageElement.textContent = message;
    notification.className = "notification";
    if (type === "error") {
        notification.classList.add("error");
        iconElement.textContent = "✕";
    } else {
        iconElement.textContent = "✓";
    }

    // 显示通知
    notification.classList.add("show");

    // 3秒后自动隐藏
    setTimeout(() => {
        notification.classList.remove("show");
    }, 3000);
}

// 切换显示更多/收起回复
function toggleReplies(commentId, totalReplies) {
    const container = document.getElementById(`repliesContainer${commentId}`);
    const remainingReplies = container.querySelector(".remaining-replies");
    const toggleButton = container.querySelector(".toggle-replies");
    const showMoreText = toggleButton.querySelector(".show-more");
    const showLessText = toggleButton.querySelector(".show-less");

    if (remainingReplies.style.display === "none") {
        remainingReplies.style.display = "block";
        showMoreText.style.display = "none";
        showLessText.style.display = "inline";
    } else {
        remainingReplies.style.display = "none";
        showMoreText.style.display = "inline";
        showLessText.style.display = "none";
    }
}

document.addEventListener("DOMContentLoaded", function () {
    const inputDemand = document.getElementById("input-demand");
    const confirmSubBtn = document.getElementById("confirmsub-btn");
    const demandDescription = document.getElementById("demand-description");
    const demandDescriptionone = document.getElementById(
        "demand-description-one"
    );
    const mindmapContainer = document.getElementById("load-mindmap-container");

    let isWaitingForResponse = false;
    let conversationId = "";
    let markmapInstance = null;
    let transformer = null;

    // 等待库加载完成
    function waitForMarkmap() {
        return new Promise((resolve) => {
            const check = () => {
                if (window.markmap && window.markmap.Markmap) {
                    resolve();
                } else {
                    setTimeout(check, 100);
                }
            };
            check();
        });
    }

    // 生成思维导图
    async function generateMindmap(markdownContent) {
        try {
            if (!appState.mindmapContainer) {
                console.error("找不到mindmap-container元素");
                return;
            }

            if (!markdownContent || markdownContent.trim() === "") {
                appState.mindmapContainer.innerHTML =
                    '<div class="mindmap-placeholder">请在右侧输入需求内容，将自动生成思维导图</div>';
                appState.currentMarkmapInstance = null;
                return;
            }

            // 等待库加载
            await waitForMarkmap();

            // 如果内容不是markdown格式，尝试转换为简单的markdown结构
            let processedContent = markdownContent;
            if (
                !markdownContent.includes("#") &&
                !markdownContent.includes("*") &&
                !markdownContent.includes("-")
            ) {
                // 简单文本转换为markdown格式
                const lines = markdownContent.split("\n").filter((line) => line.trim());
                if (lines.length > 0) {
                    processedContent = `# ${lines[0]}\n\n${lines
                        .slice(1)
                        .map((line) => `- ${line}`)
                        .join("\n")}`;
                }
            }

            // 初始化transformer（如果还没有）
            if (!transformer) {
                transformer = new window.markmap.Transformer();
            }

            // 使用markmap-lib解析markdown
            const { root } = transformer.transform(processedContent);

            // 初始化或更新markmap
            if (
                !appState.currentMarkmapInstance ||
                !appState.mindmapContainer.querySelector("svg")
            ) {
                // 清空容器
                appState.mindmapContainer.innerHTML = "";

                // 创建SVG元素
                const svg = document.createElementNS(
                    "http://www.w3.org/2000/svg",
                    "svg"
                );
                svg.style.width = "100%";
                svg.style.height = "100%";
                appState.mindmapContainer.appendChild(svg);

                // 创建新的Markmap实例
                appState.currentMarkmapInstance = new window.markmap.Markmap(svg, {
                    autoFit: true,
                    duration: 300,
                    maxWidth: 300,
                    color: (node) => {
                        const colors = [
                            "#4CAF50",
                            "#2196F3",
                            "#FF9800",
                            "#9C27B0",
                            "#F44336",
                        ];
                        return colors[node.depth % colors.length];
                    },
                });
            }

            if (appState.currentMarkmapInstance && root) {
                // 渲染思维导图
                appState.currentMarkmapInstance.setData(root);
                appState.currentMarkmapInstance.fit();
            }
        } catch (error) {
            console.error("生成思维导图失败:", error);
            appState.mindmapContainer.innerHTML =
                '<div class="mindmap-placeholder">思维导图生成失败，请检查内容格式</div>';
            appState.currentMarkmapInstance = null;
        }
    }

    // 监听需求描述变化，自动生成思维导图
    let mindmapTimer = null;
    async function onDescriptionChange() {
        // 防抖处理，避免频繁更新
        if (mindmapTimer) {
            clearTimeout(mindmapTimer);
        }

        mindmapTimer = setTimeout(async () => {
            const content = demandDescription.value;
            await generateMindmap(content);
        }, 500); // 500ms延迟
    }

    // 绑定文本框变化事件
    demandDescription.addEventListener("input", onDescriptionChange);
    demandDescription.addEventListener("change", onDescriptionChange);

    // 显示加载指示器
    function showLoadingIndicator() {
        // 在需求描述区域显示加载中提示
        demandDescription.value = "正在生成需求描述，请稍候...";
        demandDescription.disabled = true;

        // 在思维导图区域显示加载提示
        appState.mindmapContainer.innerHTML =
            '<div class="mindmap-placeholder">正在生成思维导图...</div>';
    }

    // 移除加载指示器
    function removeLoadingIndicator() {
        demandDescription.disabled = false;
    }

    // 发送需求到服务器 - 支持流式响应
    async function sendDemand(demand) {
        try {
            // 显示加载指示器
            showLoadingIndicator();

            // 准备请求数据
            const requestData = {
                query: demand,
                user: "publisher-user-" + Date.now(),
                inputs: {},
                response_mode: "streaming",
                conversation_id: conversationId,
            };

            // 发送请求
            const response = await fetch("/api/chat", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(requestData),
            });

            if (!response.ok || !response.body) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let accumulatedAnswer = ""; // 累积的answer内容
            let buffer = ""; // 缓冲区用于处理不完整的数据行
            let firstDataReceived = false; // 标记是否已收到第一个数据

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                // 解码chunk并添加到缓冲区
                buffer += decoder.decode(value, { stream: true });

                // 按行分割数据
                const lines = buffer.split("\n");

                // 保留最后一行（可能不完整）作为缓冲区
                buffer = lines.pop() || "";

                // 处理每一行
                for (const line of lines) {
                    const trimmedLine = line.trim();

                    // 跳过空行
                    if (!trimmedLine) continue;

                    // 处理以 "data: " 开头的行
                    if (trimmedLine.startsWith("data: ")) {
                        const jsonStr = trimmedLine.substring(6); // 移除 "data: " 前缀

                        try {
                            const data = JSON.parse(jsonStr);

                            // 提取answer内容
                            if (data.answer) {
                                // 如果是第一次接收到数据，清空加载提示
                                if (!firstDataReceived) {
                                    demandDescription.value = "";
                                    firstDataReceived = true;
                                }

                                accumulatedAnswer += data.answer;
                                // 实时更新文本框内容
                                demandDescription.value = accumulatedAnswer;

                                // 实时更新思维导图
                                await onDescriptionChange();
                            }

                            // 更新conversation_id
                            if (data.conversation_id) {
                                conversationId = data.conversation_id;
                            }

                            // 可以根据需要处理其他事件类型
                            if (data.event) {
                                console.log("Event:", data.event);
                            }
                        } catch (parseError) {
                            console.warn("解析JSON失败:", parseError, "原始数据:", jsonStr);
                        }
                    }
                }
            }

            // 处理缓冲区中剩余的数据
            if (buffer.trim()) {
                const trimmedLine = buffer.trim();
                if (trimmedLine.startsWith("data: ")) {
                    const jsonStr = trimmedLine.substring(6);
                    try {
                        const data = JSON.parse(jsonStr);
                        if (data.answer) {
                            // 如果是第一次接收到数据，清空加载提示
                            if (!firstDataReceived) {
                                demandDescription.value = "";
                                firstDataReceived = true;
                            }

                            accumulatedAnswer += data.answer;
                            demandDescription.value = accumulatedAnswer;

                            // 最终更新思维导图
                            await onDescriptionChange();
                        }
                        if (data.conversation_id) {
                            conversationId = data.conversation_id;
                        }
                    } catch (parseError) {
                        console.warn("解析最后数据失败:", parseError);
                    }
                }
            }

            console.log("流式响应完成，总内容长度:", accumulatedAnswer.length);
        } catch (error) {
            console.error("发送需求错误:", error);
            demandDescription.value = `发送需求失败: ${error.message}`;
            appState.mindmapContainer.innerHTML =
                '<div class="mindmap-placeholder">生成失败，请重试</div>';
        } finally {
            isWaitingForResponse = false;
            inputDemand.disabled = false;
            confirmSubBtn.disabled = false;
            removeLoadingIndicator();
        }
    }

    // 绑定确认按钮点击事件
    confirmSubBtn.addEventListener("click", function () {
        const demand = inputDemand.value.trim();
        if (!demand) {
            alert("请输入需求内容");
            return;
        }

        if (isWaitingForResponse) {
            alert("正在处理中，请稍候...");
            return;
        }

        isWaitingForResponse = true;
        inputDemand.disabled = true;
        confirmSubBtn.disabled = true;

        // 发送需求
        sendDemand(demand);
    });

    // 支持回车键发送（Ctrl+Enter）
    inputDemand.addEventListener("keydown", function (e) {
        if (e.ctrlKey && e.key === "Enter") {
            e.preventDefault();
            confirmSubBtn.click();
        }
    });

    // 初始化时显示占位符
    appState.mindmapContainer.innerHTML =
        '<div class="mindmap-placeholder">请在右侧输入需求内容，将自动生成思维导图</div>';

    // 预加载Markmap库
    waitForMarkmap()
        .then(() => {
            console.log("Markmap库加载完成");
        })
        .catch((error) => {
            console.error("Markmap库加载失败:", error);
        });
});

// 初始化脑图渲染器
let currentMindmap = null;

// 保存需求更改并记录历史
async function saveDemandChanges(demandId) {
    const saveButton = document.querySelector(".save-btn");
    const originalButtonText = saveButton.innerHTML;

    try {
        // 显示保存中状态
        saveButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
        saveButton.disabled = true;

        const descriptionTextarea = document.getElementById(
            "demand-description-one"
        );
        const mindmapContainer = document.getElementById(
            "maintenance-mindmap-container-one"
        );

        if (!descriptionTextarea) {
            throw new Error("Description textarea not found");
        }

        // 获取当前值
        const newDescription = descriptionTextarea.value.trim();
        let newMindMapData = null;

        // 获取脑图数据
        if (
            appState.currentMarkmapInstance &&
            appState.currentMarkmapInstance.state &&
            appState.currentMarkmapInstance.state.data
        ) {
            newMindMapData = JSON.stringify(
                appState.currentMarkmapInstance.state.data
            );
        } else if (mindmapContainer.querySelector("svg")) {
            newMindMapData = mindmapContainer.querySelector("svg").outerHTML;
        }

        // 获取原始需求数据
        const response = await fetch(`/api/demands/${demandId}`, {
            credentials: "include",
        });

        if (!response.ok) {
            throw new Error("Failed to fetch original demand data");
        }

        const originalDemand = await response.json();

        // 检查是否有变化
        const hasDescriptionChanged = newDescription !== originalDemand.description;
        const hasMindMapChanged = newMindMapData !== originalDemand.mindMapData;

        if (!hasDescriptionChanged && !hasMindMapChanged) {
            showNotification("没有检测到更改", "info");
            return;
        }

        // 准备更新的数据
        const updateData = {
            ...originalDemand,
            description: newDescription || originalDemand.description,
            mindMapData: newMindMapData || originalDemand.mindMapData,
        };

        // 保存更改
        const updateResponse = await fetch(`/api/demands/${demandId}`, {
            method: "PUT",
            headers: {
                "Content-Type": "application/json",
            },
            credentials: "include",
            body: JSON.stringify(updateData),
        });

        if (!updateResponse.ok) {
            throw new Error("Failed to update demand");
        }

        // 记录历史 - 创建一条历史记录
        const historyResponse = await fetch("/api/demand-history/both", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            credentials: "include",
            body: JSON.stringify({
                demand: originalDemand,
                oldDescription: originalDemand.description,
                newDescription: newDescription,
                oldMindMapData: originalDemand.mindMapData,
                newMindMapData: newMindMapData,
                modifier: {
                    id: userId,
                    email: userEmail,
                    username: userEmail,
                },
            }),
        });

        if (!historyResponse.ok) {
            throw new Error("Failed to create history record");
        }

        // 重新加载历史记录
        await loadDemandHistory(demandId);
        showNotification("保存成功！", "success");
    } catch (error) {
        console.error("Error saving demand changes:", error);
        showNotification("保存失败，请重试", "error");
    } finally {
        // 恢复按钮状态
        saveButton.innerHTML = originalButtonText;
        saveButton.disabled = false;
    }
}

// 加载需求历史记录
async function loadDemandHistory(demandId) {
    try {
        const response = await fetch(`/api/demand-history/demand/${demandId}`, {
            credentials: "include",
        });

        if (!response.ok) {
            throw new Error("Failed to fetch demand history");
        }

        const historyList = await response.json();
        const historySection = document.querySelector(".history-section");

        if (historyList.length === 0) {
            historySection.innerHTML = `
                <h3 style="margin-bottom: 12px; color: #333">历史修改：</h3>
                <div class="history-item">
                    <div class="content">暂无修改记录</div>
                </div>
            `;
            return;
        }

        const historyHtml = historyList
            .map((history) => {
                const modifierName = history.modifierName || "未知用户";
                const modificationTime = formatDateTime(history.modificationTime);
                let modificationType = "";
                switch (history.modificationType) {
                    case "DESCRIPTION_UPDATE":
                        modificationType = "需求描述更新";
                        break;
                    case "MINDMAP_UPDATE":
                        modificationType = "脑图更新";
                        break;
                    case "BOTH_UPDATE":
                        modificationType = "需求描述和脑图更新";
                        break;
                    default:
                        modificationType = "未知类型";
                }

                return `
                <div class="history-item">
                    <div class="content">
                        <div class="history-info">
                            <span class="modifier">${modifierName}</span>
                            <span class="type">${modificationType}</span>
                            <span class="time">${modificationTime}</span>
                        </div>
                    </div>
                    <button class="download-btn" onclick="downloadHistory(${history.id}, '${history.modificationType}')">
                        <i class="fas fa-download"></i>
                        回退
                    </button>
                </div>
            `;
            })
            .join("");

        historySection.innerHTML = `
            <h3 style="margin-bottom: 12px; color: #333">历史修改：</h3>
            ${historyHtml}
        `;
    } catch (error) {
        console.error("Error loading demand history:", error);
        const historySection = document.querySelector(".history-section");
        historySection.innerHTML = `
            <h3 style="margin-bottom: 12px; color: #333">历史修改：</h3>
            <div class="history-item">
                <div class="content">加载历史记录失败</div>
            </div>
        `;
    }
}

// 添加下载历史记录的函数（目前只是占位）
function downloadHistory(historyId, modificationType) {
    // 这里暂时只显示通知，实际功能后续实现
    showNotification("下载功能即将开放", "info");
}

// 监听需求描述变化
document.addEventListener("input", async function (e) {
    // 检查是否是需求描述输入框
    if (
        e.target.id === "maintenance-description" ||
        e.target.id === "demand-description-one"
    ) {
        try {
            const content = e.target.value;
            // 获取对应的mindmap容器
            const containerId =
                e.target.id === "maintenance-description"
                    ? "maintenance-mindmap-container"
                    : "maintenance-mindmap-container-one";

            if (!content || content.trim() === "") {
                document.getElementById(containerId).innerHTML =
                    '<div class="mindmap-placeholder">请在右侧输入需求描述，将自动生成思维导图</div>';
                return;
            }

            // 等待markmap库加载
            await waitForMarkmap();

            // 初始化transformer
            if (!appState.transformer) {
                appState.transformer = new window.markmap.Transformer();
            }

            // 转换markdown为mindmap数据
            const { root } = appState.transformer.transform(content);

            // 初始化或更新mindmap
            const container = document.getElementById(containerId);
            if (!container.querySelector("svg")) {
                container.innerHTML = "";
                const svg = document.createElementNS(
                    "http://www.w3.org/2000/svg",
                    "svg"
                );
                svg.style.width = "100%";
                svg.style.height = "100%";
                container.appendChild(svg);

                // 为每个容器存储自己的mindmap实例
                const mindmapKey =
                    e.target.id === "maintenance-description"
                        ? "currentMindmap"
                        : "currentMindmapOne";

                appState[mindmapKey] = new window.markmap.Markmap(svg, {
                    autoFit: true,
                    duration: 300,
                    maxWidth: 300,
                    color: (node) => {
                        const colors = [
                            "#4CAF50",
                            "#2196F3",
                            "#FF9800",
                            "#9C27B0",
                            "#F44336",
                        ];
                        return colors[node.depth % colors.length];
                    },
                });
            }

            // 更新数据
            const mindmapKey =
                e.target.id === "maintenance-description"
                    ? "currentMindmap"
                    : "currentMindmapOne";

            if (appState[mindmapKey] && root) {
                appState[mindmapKey].setData(root);
                appState[mindmapKey].fit();
            }
        } catch (error) {
            console.error("生成思维导图失败:", error);
            const containerId =
                e.target.id === "maintenance-description"
                    ? "maintenance-mindmap-container"
                    : "maintenance-mindmap-container-one";
            document.getElementById(containerId).innerHTML =
                '<div class="mindmap-placeholder">思维导图生成失败，请检查内容格式</div>';
        }
    }
});
